﻿using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace HelperFromTheSkeleton.HttpHelper
{
    public class Http
    {
        private HttpClient _httpClient;

        public Http()
        {
            var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = SslProtocols.Tls12,
                ServerCertificateCustomValidationCallback = (x, y, z, m) => true,
            };
            _httpClient = new HttpClient(handler);
        }
        public Http(X509Certificate2[] certificate2s)
        {
            var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = SslProtocols.None,
                ServerCertificateCustomValidationCallback = (x, y, z, m) => true,
            };
            foreach (var certificate2 in certificate2s)
            {
                handler.ClientCertificates.Add(certificate2);
            }
            _httpClient = new HttpClient(handler);
        }

        public string Send(HttpRequestMessage httpRequestMessage)
        {
            HttpResponseMessage httpResponseMessage = _httpClient.Send(httpRequestMessage);
            httpResponseMessage.EnsureSuccessStatusCode();
            Stream responseBodyStream = httpResponseMessage.Content.ReadAsStream();
            byte[] buffers = new byte[responseBodyStream.Length];
            responseBodyStream.Read(buffers);
            var result = Encoding.UTF8.GetString(buffers, 0, buffers.Length);
            return result;
        }

        public async Task<string> SendAsync(HttpRequestMessage httpRequestMessage)
        {
            HttpResponseMessage httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage);
            httpResponseMessage.EnsureSuccessStatusCode();
            Stream responseBodyStream = httpResponseMessage.Content.ReadAsStream();
            byte[] buffers = new byte[responseBodyStream.Length];
            responseBodyStream.Read(buffers);
            var result = Encoding.UTF8.GetString(buffers, 0, buffers.Length);
            return result;
        }
    }
}